package com.jwmp.core.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class BaseServlet extends HttpServlet {
    /**
     * uri 请求分发
     * 约定 Servlet uri 配置格式：/xxx/*，* 对应到要被访问的方法名
     * 例：Servlet 中有方法 hello(),则 访问地址为 /xxx/hello
     * 如果访问地址是 /xxx，则访问 list 方法
     */
    // uri 请求分发器：约定 Servlet url 配置格式为 /ooxx/*，* 和要调用的方法同名
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        int index = uri.lastIndexOf("/");
        String methodName = index == 0 ? "list" : uri.substring(index + 1);
        try {
            this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class).invoke(this,req,resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            resp.sendError(404,"method: " + methodName + " : " + e);
        } catch (Exception e){
            e.printStackTrace();
            resp.sendError(500," : " + e.getMessage());
        }
    }

    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        resp.sendError(405,"uri not method name");
    }
}
